package com.zhanggm.springcloud.zuul.filter;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zhanggm.springcloud.common.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class AuthFiler extends ZuulFilter {

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 过滤类型，pre
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否需要过滤
     * @return
     */
    @Override
    public boolean shouldFilter() {
        log.info("authFilter:shouldFilter");
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        HttpServletResponse response = requestContext.getResponse();
        String token = request.getHeader("token");
        //放行登录接口
        String requestURI = request.getRequestURI();
        if("/api/doctor/login".equals(requestURI)){
            return false;
        }
        if(token==null){
            //不路由到后端服务
            requestContext.setSendZuulResponse(false);
            try {
                //设置返回数据类型和字符集
                response.setContentType("application/json;charset=utf-8");
                ResponseResult fail = ResponseResult.fail(10000);
                response.getWriter().append(JSON.toJSONString(fail));
                requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        log.info("authFilter:run");
        //获取前端token内容
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        HttpServletResponse response = requestContext.getResponse();
        String token = request.getHeader("token");
        //连接redis服务，验证token是否正确
//        Boolean aBoolean = redisTemplate.hasKey(token);
        Object userInfoJsonStr = redisTemplate.opsForValue().get(token);
        if(userInfoJsonStr==null){
            //如果不正确
            //不路由到后端服务
            requestContext.setSendZuulResponse(false);
            //设置http状态码
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            //设置返回数据类型和字符集
            response.setContentType("application/json;charset=utf-8");
            ResponseResult fail = ResponseResult.fail(10000);
            try {
                response.getWriter().append(JSON.toJSONString(fail));
                return null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //token刷新
        JSONObject userInfoObject = JSON.parseObject(userInfoJsonStr.toString());
        String newToken = SecureUtil.md5(System.currentTimeMillis() + "" + userInfoObject.get("id") + request.getRemoteAddr());
        redisTemplate.opsForValue().set(newToken,userInfoJsonStr);
        //刷新redis的过期时间
        redisTemplate.expire(newToken,60, TimeUnit.SECONDS);
        //把token给到客户端
        response.setHeader("Authorization",newToken);
//        response.addCookie(new Cookie("newToken",newToken));
//        response.addHeader("token",newToken);
        System.out.println(newToken);

        return null;
    }
}
